import pickle
import numpy as np


def save_variable(v,filename):
    f = open(filename, 'wb')
    pickle.dump(v, f)
    f.close()
    return filename


def load_variable(filename):
    f = open(filename, 'rb')
    r = pickle.load(f)
    f.close()
    return r


def analyze(info, x_list, y_list, truth_x, ax, f):
    info = load_variable(info)
    print("Search finished in", info['consume'] * 1000, "ms")
    print("Best x:", info['best_x'])
    print("Best y:", info['best_y'])
    print("Worst y:", info['worst_y'])

    x_list = load_variable(x_list)
    y_list = load_variable(y_list)
    x_var = np.var(x_list)
    print("Variance x:", x_var)
    x_mean = np.mean(x_list)
    print("Mean x:", x_mean)
    print("Distance from mean x to truth:", abs(truth_x - x_mean))

    ax.cla()
    X = np.linspace(-1, 2, num=300)
    Y = f(X)
    ax.plot(X, Y)
    for x, y in zip(x_list, y_list):
        ax.plot(x, y, marker="o", markersize=2, markeredgecolor="red")
